<template>
  <ry-modal
    :title="isEdit ? '编辑采样记录' : '新增采样记录'"
    v-model="visible"
    destroyOnClose
    :confirmLoading="confirmLoading"
    :ryfooter="null"
    width="1000px"
  >
    <div class="table-container sample-record-modal-body">
      <a-form-model
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="modelConfig.labelCol"
        :wrapper-col="modelConfig.wrapperCol"
        class="sample-record-form"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-model-item label="项目名称">
              <div class="bind-project-tags">
                <template v-if="form.projects">
                  <a-tag color="blue">
                    {{$getDictName('APPLY_PROJECT', form.projects.applyProject)}}
                  </a-tag>
                </template>
                <a-button size="small" style="margin-left:8px;" @click="openProjectPicker" v-if="!form.id">选择</a-button>
              </div>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="项目数量">
              <a-input
                v-model="form.projects === undefined ? 0 : form.projects.projectNumber"
                disabled
              />
            </a-form-model-item>
          </a-col>

          <!-- =================== 客户姓名 =================== -->
          <a-col :span="12">
            <a-form-model-item label="客户姓名">
              <a-input
                v-model="form.nickname"
                disabled
                placeholder="未选择"
              />
            </a-form-model-item>
          </a-col>

          <!-- =================== 联系电话 =================== -->
          <a-col :span="12">
            <a-form-model-item label="客户编号">
              <a-input
                v-model="form.serialNumber"
                disabled
                placeholder="未选择"
              />
            </a-form-model-item>
          </a-col>
          <!-- 来源类型：下拉字典 -->
          <a-col :span="12">
            <a-form-model-item label="采样来源类型" prop="sampleSourceType">
              <ry-select v-model="form.sampleSourceType" :dataSource="$getDict('record_source')"></ry-select>
            </a-form-model-item>
          </a-col>

          <!-- 采样时间（新增显示） -->
          <a-col :span="12" v-if="!isEdit">
            <a-form-model-item label="采样时间" prop="samplTime">
              <a-date-picker
                v-model="form.samplTime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="采样地点" prop="samplLocal">
              <a-input v-model="form.samplLocal" placeholder="请输入采样地点" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="采样医生" prop="samplPerson">
              <a-input v-model="form.samplPerson" placeholder="请输入采样医生" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="样品质量" prop="samplQuality">
              <ry-select v-model="form.samplQuality" :dataSource="$getDict('sample_quality')"></ry-select>
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="样本体积" prop="sampleVolume">
              <a-input v-model="form.sampleVolume" placeholder="请输入样本体积" />
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="备注" prop="remark">
              <a-textarea v-model="form.remark" placeholder="请输入备注" :rows="3" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <!-- 按钮 -->
        <a-form-model-item :wrapper-col="{ span: 24 }" class="form-btn-row" v-if="type !== '3'">
          <div class="form-btn-group">
            <a-button type="primary" :loading="confirmLoading" @click="handleOk">提交</a-button>
            <a-button @click="handleCancel">取消</a-button>
          </div>
        </a-form-model-item>
      </a-form-model>
    </div>

    <!-- 选择客户 / 项目弹框（复用你现有组件） -->
    <ApplyProjectListModel ref="projectPicker" @project="onProjectSelected" />
  </ry-modal>
</template>

<script>
import ApplyProjectListModel from '@/views/cellManage/modules/ApplyProjectListModel.vue'

export default {
  name: 'SampleRecordModal',
  components: { ApplyProjectListModel },
  props: ['url'],
  data () {
    return {
      visible: false,
      isEdit: false,
      confirmLoading: false,
      footerType: false,
      form: {},

      sampleQualityOptions: [],

      rules: {
        sampleSourceType: [{ required: true, message: '请选择采样来源类型', trigger: 'change' }],
        samplTimeAdd: [{ required: true, message: '请选择采样时间', trigger: 'change' }],
        samplPerson: [{ required: true, message: '请输入采样人', trigger: 'blur' }],
        applyProject: [{ required: true, message: '请选择项目名称', trigger: 'change' }]
      },

      modelConfig: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 }
      }
    }
  },

  computed: {
  },

  created () {
  },

  methods: {
    add (value) {
      this.form = {}
      this.visible = true
      this.type = '1'
    },
    edit (value) {
      this.form = {}
      this.visible = true
      this.form = value
      this.type = '2'
    },
    view (value) {
      this.form = {}
      this.visible = true
      this.form = value
      this.type = '3'
    },
    /* 打开项目选择弹框（新增时用） */
    openProjectPicker () {
      this.$refs.projectPicker && this.$refs.projectPicker.open()
    },

    /* 从项目选择弹框回调中接收选中行 */
    onProjectSelected (record) {
      console.log('record', record)
      // record 模板：见你提供的“细胞信息”弹框
      const acct = record.businessAccount
      console.log('acct', acct)
      this.$set(this.form, 'projects', record)
      this.form.applyProjectId = record.id
      this.form.accountId = acct.id
      this.form.nickname = acct.nickname || ''
      this.form.serialNumber = acct.serialNumber || ''
      console.log('this.form', this.form)
    },

    handleOk () {
      console.log(this.form.applyProjectId)
      if (!this.form.applyProjectId) {
        this.$message.error('请选择项目名称')
        return
      }
      this.form.samplTime = this.normalizeTime(this.form.samplTime)
      this.confirmLoading = true
      this.$refs.formRef.validate(valid => {
        if (valid) {
          let url = this.type === '2' ? this.url.edit : this.url.add
          this.$post(url, this.form).then(res => {
            if (res.code === 200) {
              this.$message.success('添加成功')
              this.$emit('ModalOk')
            }
            this.visible = false
          })
        }
      })
      this.confirmLoading = false
    },
    normalizeTime(val) {
      if (!val) return null
      if (val && typeof val === 'object' && typeof val.format === 'function') {
        return val.format('YYYY-MM-DD HH:mm:ss')
      }
      if (val instanceof Date) {
        return this.formatDate(val)
      }
      if (typeof val === 'string') {
        return val
      }
      return null
    },

    handleCancel () {
      this.visible = false
    },

  }
}
</script>

<style scoped>
.sample-record-modal-body {
  padding: 0 8px;
}
.bind-project-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.bind-project-tags {
  flex: 1;
  min-height: 32px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 4px;
}
.bind-project-placeholder {
  color: #999;
  font-size: 12px;
}
.form-btn-row {
  margin-top: 8px;
}
.form-btn-group {
  display: flex;
  justify-content: center;
  gap: 24px;
}
</style>
